package com.drd.dt.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.drd.dt.properties.ALYPropertyConfig;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.URLEncoder;
import java.util.Random;

/**
 * 短信服务工具
 **/
@Component
public class SMSUtil {

    @Autowired
    private ALYPropertyConfig alyPropertyConfig;
    /**
     * 发送短信获取验证码
     *
     * @param phoneNumbers  手机号码
     * @param templateCode  模板ID
     * @param templateParam 短信模板变量对应的实际值，JSON格式。
     * @param smsType 短信平台类型  0 阿里 1 其他
     */
    public boolean clientReceiveSMS(String phoneNumbers,
                                           String templateCode,
                                           String templateParam,
                                            Integer smsType) {
        boolean is = false;
        switch (smsType){
            case 0:{
                String name = alyPropertyConfig.getName();
                String accessKeyid = alyPropertyConfig.getAccessKeyid();
                String accessKeysecret = alyPropertyConfig.getAccessKeysecret();
                alyPropertyConfig.getName();
                DefaultProfile profile = DefaultProfile.getProfile(name, accessKeyid,accessKeysecret);
                IAcsClient client = new DefaultAcsClient(profile);
                CommonRequest request = new CommonRequest();
                try {
                    request.setMethod(MethodType.POST);
                    request.setDomain("dysmsapi.aliyuncs.com");
                    request.setVersion("2017-05-25");
                    request.setAction("SendSms");
                    request.putQueryParameter("PhoneNumbers", phoneNumbers);
                    request.putQueryParameter("SignName", name);
                    request.putQueryParameter("TemplateCode", templateCode);
                    request.putQueryParameter("TemplateParam", "{\"code\":\"" + templateParam + "\"}");
                    CommonResponse response = client.getCommonResponse(request);
                    String data = response.getData();
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.has("Code") && jsonObject.getString("Code").equals("OK")) {
                        is = true;
                    } else {
                        System.out.println("短信发送状态：失败:" + data);
                        is = false;
                    }
                } catch (ServerException e) {
                    e.printStackTrace();
                } catch (ClientException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }break;
            case 1:{
                try {
                    String name = "clydrd168";
                    String password = "rttd75";
                    String content =   URLEncoder.encode("【核桃省钱】 验证码" + templateParam + ",您正在登录,若非本人操作，请勿泄露。","UTF-8");
                    StringBuffer url = new StringBuffer("http://www.sms-cly.cn/v6/sms/send.do?");
                    url.append("username=" + name);
                    url.append("&password=" + MD5Utils.MD5Encode(name + MD5Utils.MD5Encode(password,"UTF-8"),"UTF-8" ));
                    url.append("&mobile=" + phoneNumbers);
                    url.append("&content=" + content);
                    String req = HttpConnectionPoolUtil.get(url.toString());
                    if(!StringUtils.isEmpty(req) && req.indexOf(",") != -1){
                        String[] str  = req.split(",");
                        if (str.length > 1 && str[0].equals("1")) {
                            is = true;
                        }else{
                            System.out.println("短信发送状态：失败:" + req);
                        }
                    }else {
                        System.out.println("短信发送状态：失败:" + req);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }break;
        }
        return is;
    }

    /**
     * 随机生成验证码
     **/
    public String getSMSCode() {
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            code += random.nextInt(10);
        }
        return code;
    }
}
